<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use app\common\GptService;
use app\job\Task;
use app\model\Users;
use app\model\UsersAd;
use app\model\UsersChatgpt;
use app\Request;
use isszz\sensitive\facade\Sensitive;
use think\db\exception\DbException;
use think\Exception;
use think\facade\Log;
use think\facade\Queue;
use think\response\Json;

class GptController extends BaseController
{
	public static $ad = 3;
	
    protected $chatgpt_key='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';
    protected array $middleware=['Login'=>[
        'except'=>[''],
    ]];
	
	/**
	 * gpt-聊天记录
	 * @param Request $request
	 * @return Json
	 */
    public function index(Request $request)
    {
 
        $list=UsersChatgpt::where('users_id',$request->users_id)->order(['id'=>'desc'])->paginate()->items();
        $num= Users::where('id',$request->users_id)->value('gpt_num');
        $arr=['num'=>$num,'list'=>$list];
        writeJson($arr);
    }

    /**
     * gpt-提问
     * @param Request $request
     * @return Json
     */
    public function send_msg(Request $request)
    {
        $content=$request->post('content'); //content
	    Log::record('ChatGPT');
	    try {
		   GptService::decGptNum($request->users_id,1,$content);
	    }catch (Exception $e){
		    writeJson(0,$e->getMessage());
	    }
	    // 检测敏感词
	    if (Sensitive::is(content: $content)) {
		    $content = '[内容包含敏感信息]';
	    }
	    Queue::push(Task::class, ['data' => ['users_id' => $request->users_id, 'content' => $content], 'action' => 'SendMsg'], 'task');
	    writeJson();
    }
	
	/**
	 * 看广告
	 * @param Request $request
	 * @return Json
	 * @throws DbException
	 */
	function gpt_inc(Request $request)
	{
		$count = UsersAd::where(['users_id'=>$request->users_id])->whereTime('createtime','today')->count();
		if ($count < self::$ad){
			//增加次数
			Users::where('id',$request->users_id)->setinc('gpt_num',1);
			UsersAd::create(['users_id'=>$request->users_id]);
		}
		writeJson();
	}

 
}
